package br.com.eventoweb.view.main;

import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;

import org.jboss.seam.security.Identity;

import br.com.eventoweb.view.evento.MeusEventosUI;
import br.com.eventoweb.view.main.constants.MessagesConstants;
import br.com.eventoweb.view.main.security.EventoUser;
import br.com.webutils.MessageUtil;
import br.com.webutils.ui.AbstractFacesBean;

@Named
@SessionScoped
public class LoginUI extends AbstractFacesBean {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2596898919057177681L;

	@Inject
	private Identity identity;

	@Inject
	private MeusEventosUI meusEventosUI;

	private String urlRetorno;

	public String login() {

		/* invoca login */
		identity.login();

		if (identity.isLoggedIn()) {

			MessageUtil.addGlobalInfoMessage(
					MessagesConstants.MSG_INFO_LOGIN_SUCESSO,
					((EventoUser) identity.getUser()).getUsuario()
							.getCadastro().getRazaoSocial());

			if (this.getUrlRetorno() == null) {
				meusEventosUI.getFilter().setNome("%meuseventos%");
				return meusEventosUI.prepareSearch();
			} else {

				System.out.println("Login: " + urlRetorno);
				
//				HttpServletRequest httpServletRequest = (HttpServletRequest) FacesContext
//						.getCurrentInstance().getExternalContext().getRequest();
//				try {
//					httpServletRequest
//							.getRequestDispatcher(urlRetorno)
//							.forward(
//									httpServletRequest,
//									(HttpServletResponse) FacesContext
//											.getCurrentInstance()
//											.getExternalContext().getResponse());
//				} catch (ServletException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				} catch (IOException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
				return urlRetorno;
			}
		}

		return null;
	}

	public String prepareLogin() {
		return "/login.xhtml";
	}

	public String getUrlRetorno() {
		return urlRetorno;
	}

	public void setUrlRetorno(String urlRetorno) {
		this.urlRetorno = urlRetorno;
	}

}
